package cn.aitrox.ry.service.anno.dao.impl;

import cn.aitrox.ry.common.bean.Order;
import cn.aitrox.ry.common.dao.MapperSqlCallback;
import cn.aitrox.ry.common.dao.impl.BaseDaoImpl;
import cn.aitrox.ry.service.anno.dao.TaskDao;
import cn.aitrox.ry.service.anno.entity.TaskEntity;
import cn.aitrox.ry.service.anno.mapper.TaskMapper;
import cn.aitrox.ry.service.anno.po.task.TaskFindCondPo;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class TaskDaoImpl extends BaseDaoImpl<TaskEntity> implements TaskDao {

    @Autowired
    private TaskMapper mapper;

    @Override
    public PageInfo<TaskEntity> searchByCustom(Integer page, Integer pageSize, TaskFindCondPo cond) {
        return searchByCustom(page, pageSize, Order.desc("id"), new MapperSqlCallback<TaskEntity>() {
            @Override
            public List<TaskEntity> invoke() {
                return mapper.findByCond(cond);
            }
        });
    }

    @Override
    public void updateStatusById(Integer id, Integer status) {
        TaskEntity update = new TaskEntity();
        update.setId(id);
        update.setStatus(status);

        updateByIdSelective(update);
    }

    @Override
    public PageInfo<TaskEntity> joinableSearch(Integer page, Integer pageSize, String keyword, Integer userId, Integer status) {
        Integer taskId = null;
        String likeName = null;
        if (StringUtils.isNotEmpty(keyword)) {
            if (NumberUtils.isDigits(keyword)) {
                try {
                    taskId = Integer.parseInt(keyword);
                } catch (NumberFormatException e) {
                }
            }
            String likeKeword = "%" + keyword + "%";
            likeName = likeKeword;
        }
        final Integer finalTaskId = taskId;
        final String finalLikeName = likeName;
        return searchByCustom(page, pageSize, Order.desc("id"), new MapperSqlCallback<TaskEntity>() {
            @Override
            public List<TaskEntity> invoke() {
                return mapper.findJoinableByKeyword(userId, status, finalTaskId, finalLikeName, 1);
            }
        });
    }
}
